<?php
/**
 * Created by 枫叶情缘.
 * User: Administrator
 * Date: 2020/6/26
 * Time: 15:27
 */


use think\DbManager;
require_once   __DIR__.'/vendor/autoload.php';


/**
 * Class thinkOrm
 *
 *    总共39个函数
 */
class   thinkOrm  extends  DbManager {
    var $link_id    = NULL;

    var $settings   = array();

    var $queryCount = 0;
    var $queryTime  = '';
    var $queryLog   = array();

    var $max_cache_time = 300; // 最大的缓存时间，以秒为单位

    var $cache_data_dir = 'temp/query_caches/';
    var $root_path      = '';

    var $error_message  = array();
    var $platform       = '';
    var $version        = '';
    var $dbhash         = '';
    var $starttime      = 0;
    var $timeline       = 0;
    var $timezone       = 0;

    var $mysql_config_cache_file_time = 0;

    var $mysql_disable_cache_tables = array(); // 不允许被缓存的表，遇到将不会进行缓存

    var $dbname;

    var $table;

    var  $init = false;


    function __construct($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'utf8', $pconnect = 0, $quiet = 0)
    {

        $this->_connect($dbhost, $dbuser, $dbpw, $dbname, $charset, $pconnect, $quiet);
        $this->dbname = $dbname;
        parent::__construct();

        $this->link_id = $this;


        $db_version     =  $this->query('select version();');
        $db_version     =  $db_version? $db_version[0]['version()'] : 0;
        $this->version  =  $db_version;

    }

    public  function _connect($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'utf8', $pconnect = 0, $quiet = 0)
    {
          $this->setConfig([
              // 默认数据连接标识
              'default'     => 'mysql',
              // 数据库连接信息
              'connections' => [
                  'mysql' => [
                      // 数据库类型
                      'type'     => 'mysql',
                      // 主机地址
                      'hostname' => $dbhost,
                      // 用户名
                      'username' => $dbuser,
                      'password' => $dbpw,
                      // 数据库名
                      'database' => $dbname,
                      // 数据库编码默认采用utf8
                      'charset'  => $charset,
                      // 数据库表前缀
                      'prefix'   => '',
                      // 数据库调试模式
                      'debug'    => false,
                  ],
              ],
          ]);
    }

    function select_database($dbname)
    {
        return  $this->link_id;
    }

    function set_mysql_charset($charset)
    {
        return  true;
    }

    function fetch_array($query, $result_type = MYSQL_ASSOC)
    {

    }

    function query($sql, $parse = false)
    {

        if (stripos(trim($sql), 'show') === 0 || stripos(trim($sql), 'select') === 0 || stripos(trim($sql), 'desc') === 0) {
            return parent::query($sql);
        } else {
            return parent::execute($sql); //不是查询条件，直接执行
        }
    }

    function affected_rows()
    {

    }

    function error()
    {
        return mysqli_error($this->db);
    }

    function errno()
    {
        return mysqli_errno($this->db);
    }

    function result($query, $row)
    {



    }

    function num_rows($query)
    {

        return  $query->getNumRows();

    }

    function num_fields($query)
    {
           
    }

    function free_result($query)
    {
           

    }

    function insert_id()
    {
        return  $this->getLastInsID();
    }

    function fetchRow(&$query){
        
        if(!is_array($query) || count($query) == 0){
              return  array();
        }
        $result =  array_shift($query);
        return  $result;
    }

    function fetch_fields($query)
    {

    }

    function version()
    {
        return $this->version;
    }

    function ping()
    {
        return  true;
    }

    static function escape_string($unescaped_string)
    {
          return  true;
    }

    function close()
    {
        parent::close();
        return true;
    }

    function ErrorMsg($message = '', $sql = '')
    {
        if ($message)
        {
            echo "<b>DSC info</b>: $message\n\n<br /><br />";
            //print('<a href="http://faq.comsenz.com/?type=mysql&dberrno=2003&dberror=Can%27t%20connect%20to%20MySQL%20server%20on" target="_blank">http://faq.comsenz.com/</a>');
        }
        else
        {
            echo "<b>MySQL server error report:";
            print_r($this->error_message);
            //echo "<br /><br /><a href='http://faq.comsenz.com/?type=mysql&dberrno=" . $this->error_message[3]['errno'] . "&dberror=" . urlencode($this->error_message[2]['error']) . "' target='_blank'>http://faq.comsenz.com/</a>";
        }

        exit;
    }


    function selectLimit($sql, $num, $start = 0)
    {
        if ($start == 0)
        {
            $sql .= ' LIMIT ' . $num;
        }
        else
        {
            $sql .= ' LIMIT ' . $start . ', ' . $num;
        }

        return $this->query($sql);
    }

    function getOne($sql, $limited = true)
    {
        if ($limited == true)
        {
            $sql = trim($sql . ' LIMIT 1');
        }

        $res = $this->query($sql);
        if ($res !== false)
        {
            $row = mysql_fetch_row($res);

            if ($row !== false)
            {
                return $row[0];
            }
            else
            {
                return '';
            }
        }
        else
        {
            return false;
        }
    }

    function getOneCached($sql, $cached = 'FILEFIRST')
    {
          return false;
    }

    function getAll($sql)
    {
        $res = $this->query($sql);
        if ($res !== false) {
            $arr = [];
            foreach ($res as $row) {
                $arr[] = $row;
            }
            return $arr;
        } else {
            return [];
        }
    }

    function getAllCached($sql, $cached = 'FILEFIRST')
    {

    }

    function getRow($sql, $limited = false)
    {
        if ($limited == true) {
            $sql = trim($sql . ' LIMIT 1');
        }

        $res = $this->query($sql);
        return isset($res[0]) ? $res[0] : [];

    }

    function getRowCached($sql, $cached = 'FILEFIRST')
    {
        return false;
    }

    function getCol($sql)
    {
        $res = $this->query($sql);
        if ($res !== false) {
            $arr = [];
            foreach ($res as $row) {
                $arr[] = current($row);
            }

            return $arr;
        } else {
            return [];
        }
    }

    function getColCached($sql, $cached = 'FILEFIRST')
    {
        return false;
    }

    function autoExecute($table, $field_values, $mode = 'INSERT', $where = '', $querymode = '')
    {
        $field_names = $this->getCol('DESC ' . $table);

        $sql = '';
        if ($mode == 'INSERT') {
            $fields = $values = [];
            foreach ($field_names as $value) {
                if (array_key_exists($value, $field_values) == true) {
                    $fields[] = $value;
                    $values[] = "'" . $field_values[$value] . "'";
                }
            }

            if (!empty($fields)) {
                $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
            }
        } else {
            $sets = [];
            foreach ($field_names as $value) {
                if (array_key_exists($value, $field_values) == true) {
                    $sets[] = $value . " = '" . $field_values[$value] . "'";
                }
            }

            if (!empty($sets)) {
                $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $sets) . ' WHERE ' . $where;
            }
        }

        if ($sql) {
            return $this->query($sql);
        } else {
            return false;
        }

    }

    function autoReplace($table, $field_values, $update_values, $where = '', $querymode = '')
    {
        $field_descs = $this->getAll('DESC ' . $table);

        $primary_keys = array();
        foreach ($field_descs AS $value)
        {
            $field_names[] = $value['Field'];
            if ($value['Key'] == 'PRI')
            {
                $primary_keys[] = $value['Field'];
            }
        }

        $fields = $values = array();
        foreach ($field_names AS $value)
        {
            if (array_key_exists($value, $field_values) == true)
            {
                $fields[] = $value;
                $values[] = "'" . $field_values[$value] . "'";
            }
        }

        $sets = array();
        foreach ($update_values AS $key => $value)
        {
            if (array_key_exists($key, $field_values) == true)
            {
                if (is_int($value) || is_float($value))
                {
                    $sets[] = $key . ' = ' . $key . ' + ' . $value;
                }
                else
                {
                    $sets[] = $key . " = '" . $value . "'";
                }
            }
        }

        $sql = '';
        if (empty($primary_keys))
        {
            if (!empty($fields))
            {
                $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
            }
        }
        else
        {
            if ($this->version() >= '4.1')
            {
                if (!empty($fields))
                {
                    $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
                    if (!empty($sets))
                    {
                        $sql .=  'ON DUPLICATE KEY UPDATE ' . implode(', ', $sets);
                    }
                }
            }
            else
            {
                if (empty($where))
                {
                    $where = array();
                    foreach ($primary_keys AS $value)
                    {
                        if (is_numeric($value))
                        {
                            $where[] = $value . ' = ' . $field_values[$value];
                        }
                        else
                        {
                            $where[] = $value . " = '" . $field_values[$value] . "'";
                        }
                    }
                    $where = implode(' AND ', $where);
                }

                if ($where && (!empty($sets) || !empty($fields)))
                {
                    if (intval($this->getOne("SELECT COUNT(*) FROM $table WHERE $where")) > 0)
                    {
                        if (!empty($sets))
                        {
                            $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $sets) . ' WHERE ' . $where;
                        }
                    }
                    else
                    {
                        if (!empty($fields))
                        {
                            $sql = 'REPLACE INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
                        }
                    }
                }
            }
        }

        if ($sql)
        {
            return $this->query($sql, $querymode);
        }
        else
        {
            return false;
        }
    }

    function setMaxCacheTime($second)
    {
        $this->max_cache_time = $second;
    }

    function getMaxCacheTime()
    {
        return $this->max_cache_time;
    }

    function getSqlCacheData($sql, $cached = '')
    {
        return  false;
    }

    function setSqlCacheData($result, $data)
    {
        return false;
    }

    /* 获取 SQL 语句中最后更新的表的时间，有多个表的情况下，返回最新的表的时间 */
    function table_lastupdate($tables)
    {
        return false;
    }

    function get_table_name($query_item)
    {

        $query_item = trim($query_item);
        $table_names = array();

        /* 判断语句中是不是含有 JOIN */
        if (stristr($query_item, ' JOIN ') == '')
        {
            /* 解析一般的 SELECT FROM 语句 */
            if (preg_match('/^SELECT.*?FROM\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?(?:(?:\s*AS)?\s*`?\w+`?)?(?:\s*,\s*(?:`?\w+`?\s*\.\s*)?`?\w+`?(?:(?:\s*AS)?\s*`?\w+`?)?)*)/is', $query_item, $table_names))
            {
                $table_names = preg_replace('/((?:`?\w+`?\s*\.\s*)?`?\w+`?)[^,]*/', '\1', $table_names[1]);

                return preg_split('/\s*,\s*/', $table_names);
            }
        }
        else
        {
            /* 对含有 JOIN 的语句进行解析 */
            if (preg_match('/^SELECT.*?FROM\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?)(?:(?:\s*AS)?\s*`?\w+`?)?.*?JOIN.*$/is', $query_item, $table_names))
            {
                $other_table_names = array();
                preg_match_all('/JOIN\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?)\s*/i', $query_item, $other_table_names);

                return array_merge(array($table_names[1]), $other_table_names[1]);
            }
        }

        return $table_names;

    }

    /* 设置不允许进行缓存的表 */
    function set_disable_cache_tables($tables)
    {
             return  true;
    }



}